package at.fhooe.obd.gui;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class PositionActivity extends Activity implements OnItemClickListener
{
	String[] longitude = null;
	String[] latitude = null;
	String[] altitude = null;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_position);
		
		longitude =  (String[])getIntent().getExtras().get(Keys.JSON_LONGITUDE);
		latitude =  (String[])getIntent().getExtras().get(Keys.JSON_LATITUDE);
		altitude =  (String[])getIntent().getExtras().get(Keys.JSON_ALTITUDE);
		
		String[] combinationLabels = new String[longitude.length];
		
		for (int i = 0; i < longitude.length; i++)
		{
			combinationLabels[i] = longitude[i] + ";" + latitude[i] + ";" + altitude[i] + ";";
		}
		
		ListView lv = (ListView) findViewById(R.id.lv_position);
		lv.setOnItemClickListener(this);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_list_item_1,
				combinationLabels);

		lv.setAdapter(adapter);
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_position, menu);
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View lv, int arg2, long arg3)
	{
		if (lv instanceof TextView)
		{
			TextView tv = (TextView)lv;
			
			String text = tv.getText().toString();
			String longitude = null;
			String latitude = null;
			
			try
			{
				longitude = text.substring(0, text.indexOf(";"));
				String latitudeSub = text.substring(text.indexOf(";") + 1);
				latitude = latitudeSub.substring(0, text.indexOf(";") - 1);
				
				// From the internet example, it works... 
//				latitude = "13.042206";
//				longitude = "80.17000";
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			
			if (longitude != null && latitude != null)
			{
				// check if longitude and latitude are parsed correctly, they are...
//				Log.i("", longitude);
//				Log.i("", latitude);
				
				Uri uri = Uri.parse("geo:" + latitude.trim() + "," + 
						longitude.trim() + "?q=" + latitude + "," + longitude + "(The position!)" + "&z=10");
				
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
			}
			
			
		}
		
	}

}
